import { FileLayerType, LayerType } from '@/enum/cimup';

// cimup 引擎图层类型名称转化
export const getLayerType = (type: string) => {
  // TODO 定义文件类型和图层类型映射关系
  return (FileLayerType as any)[type] || LayerType[type] || 'UNKNOWN';
};

// 资源路径
export const getResPath = (path?: string) => {
  if (!path) return '';
  if (path.indexOf('http') === 0) {
    return path;
  }

  let result = path;
  if (result.indexOf('gis/') === 0) {
    result = result.substring(4);
  } else if (result.indexOf('play/') === 0) {
    result = result.substring(5);
  }

  result = '/res/' + result;
  return result;
};

// 获取geojson资源类型
export const getGeoJsonType = async (dataSourceUrl: string) => {
  let type = 'UNKNOWN';

  const geojson = await loadJSON(getResPath(dataSourceUrl));
  const features = geojson?.features || [];

  for (let index = 0; index < features.length; index++) {
    const geometryType = features[index].geometry.type;
    if (geometryType.includes('Polygon')) {
      type = 'POLYGON';
      break;
    } else if (geometryType.includes('Point')) {
      type = 'POINT';
      break;
    } else if (geometryType.includes('LineString')) {
      type = 'POLYLINE';
      break;
    }
  }

  return type;
};

/**
 * 获取JSON数据
 */
export async function loadJSON(path: string) {
  let data: any = {};
  try {
    const response = await fetch(path);
    data = await response.json();
  } catch (error) {
    console.error(error);
  }
  return data;
}
